package com.xxx.base.util;

import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import org.slf4j.spi.LocationAwareLogger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.function.Supplier;

/**
 * 通用 Log
 * 1. 支持 log.debug("user name is {0.name}, age is {0.age}", user)
 *    name和age 是 user对象的一个属性.
 *    这样做的好处是: 只有当debug为true时才会去计算 user.getName();
 * 2. 支持日志前后缀
 * 依赖 slf4j
 * common log function.
 * @author hubert
 */
public class Log {
    /**
     * delegate logger.
     */
    private final LocationAwareLogger logger;
    /**
     * 日志前缀提供器
     */
    private Supplier<String> prefixSupplier;
    /**
     * 日志后缀提供器
     */
    private Supplier<String> suffixSupplier;
    private static final Object[] EMPTY = new Object[0];
    private static final boolean POST_1_6;
    private static final Method LOG_METHOD;
    private static final String FQCN = Log.class.getName();

    static {
        Method[] methods = LocationAwareLogger.class.getDeclaredMethods();
        Method logMethod = null;
        boolean post16 = false;
        for (Method method : methods) {
            if (method.getName().equals("log")) {
                logMethod = method;
                Class<?>[] parameterTypes = method.getParameterTypes();
                post16 = parameterTypes.length == 6;
                break;
            }
        }
        if (logMethod == null) {
            throw new NoSuchMethodError("Cannot find LocationAwareLogger.log() method");
        }
        POST_1_6 = post16;
        LOG_METHOD = logMethod;
    }


    private Log(LocationAwareLogger logger) {
        this.logger = logger;
    }

    public static Log of(Class<?> clazz) {
        return new Log((LocationAwareLogger) LoggerFactory.getLogger(clazz));
    }
    public static Log of(String name) {
        return new Log((LocationAwareLogger) LoggerFactory.getLogger(name));
    }

    protected void doLog(final Level level, final String loggerClassName, final String message, final Object[] pArgs, final Throwable thrown) {
        if (isEnabled(level)) {
            StringBuilder sb = new StringBuilder();
            if (prefixSupplier != null) sb.append(prefixSupplier.get()).append(message);
            else sb.append(message);
            if (suffixSupplier != null) sb.append(suffixSupplier.get());
            final String text = Msg.format(sb.toString(), pArgs);
            doLog(logger, loggerClassName, translate(level), text, thrown);
        }
    }


    protected void doLogf(final Level level, final String loggerClassName, final String format, final Object[] parameters, final Throwable thrown) {
        if (isEnabled(level)) {
            final String text = String.format(format, parameters);
            doLog(logger, loggerClassName, translate(level), text, thrown);
        }
    }


    private static void doLog(LocationAwareLogger logger, String className, int level, String text, Throwable thrown) {
        try {
            if (POST_1_6) {
                LOG_METHOD.invoke(logger, null, className, Integer.valueOf(level), text, EMPTY, thrown);
            } else {
                LOG_METHOD.invoke(logger, null, className, Integer.valueOf(level), text, thrown);
            }
        } catch (InvocationTargetException e) {
            try {
                throw e.getCause();
            } catch (RuntimeException ex) {
                throw ex;
            } catch (Error er) {
                throw er;
            } catch (Throwable throwable) {
                throw new UndeclaredThrowableException(throwable);
            }
        } catch (IllegalAccessException e) {
            throw new IllegalAccessError(e.getMessage());
        }
    }

    private static int translate(Level level) {
        if (level != null) switch (level) {
            case ERROR: return LocationAwareLogger.ERROR_INT;
            case WARN:  return LocationAwareLogger.WARN_INT;
            case INFO:  return LocationAwareLogger.INFO_INT;
            case DEBUG: return LocationAwareLogger.DEBUG_INT;
            case TRACE: return LocationAwareLogger.TRACE_INT;
        }
        return LocationAwareLogger.TRACE_INT;
    }


    // ====================log method ==============

    public void error(String pMsg, Object... pArgs) {
        doLog(Level.ERROR, FQCN, pMsg, pArgs, null);
    }

    public void error(Throwable t) {
        doLog(Level.ERROR, FQCN, "", null, t);
    }



    public void error(Throwable t, String pMsg, Object... pArgs) {
        doLog(Level.ERROR, FQCN, pMsg, pArgs, t);
    }


    public void warn(Throwable t, String pMsg, Object... pArgs) {
        doLog(Level.WARN, FQCN, pMsg, pArgs, t);
    }


    public void warn(String pMsg, Object... pArgs) {
        doLog(Level.WARN, FQCN, pMsg, pArgs, null);
    }


    public void info(String pMsg, Object... pArgs) {
        doLog(Level.INFO, FQCN, pMsg, pArgs, null);
    }

    public void info(Throwable t, String pMsg, Object... pArgs) {
        doLog(Level.INFO, FQCN, pMsg, pArgs, t);
    }


    public void debug(String pMsg, Object... pArgs) {
        doLog(Level.DEBUG, FQCN, pMsg, pArgs, null);
    }


    public void debug(Throwable t, String pMsg, Object... pArgs) {
        doLog(Level.DEBUG, FQCN, pMsg, pArgs, t);
    }



    public void trace(String pMsg, Object... pArgs) {
        doLog(Level.TRACE, FQCN, pMsg, pArgs, null);
    }


    public void trace(Throwable t, String pMsg, Object... pArgs) {
        doLog(Level.TRACE, FQCN, pMsg, pArgs, t);
    }



    // ====================log method ==============
    private boolean isEnabled(final Level level) {
        if (level != null) switch (level) {
            case ERROR: return logger.isErrorEnabled();
            case WARN:  return logger.isWarnEnabled();
            case INFO:  return logger.isInfoEnabled();
            case DEBUG: return logger.isDebugEnabled();
            case TRACE: return logger.isTraceEnabled();
        }
        return true;
    }


    public boolean isInfoEnabled() {
        return logger.isInfoEnabled();
    }



    public boolean isWarnEnabled() {
        return logger.isWarnEnabled();
    }



    public boolean isErrorEnabled() {
        return logger.isErrorEnabled();
    }



    public boolean isDebugEnabled() {
        return logger.isDebugEnabled();
    }



    public boolean isTraceEnabled() {
        return logger.isTraceEnabled();
    }


    public Log setPrefixSupplier(Supplier<String> prefixSupplier) {
        this.prefixSupplier = prefixSupplier;
        return this;
    }

    public Log setSuffixSupplier(Supplier<String> suffixSupplier) {
        this.suffixSupplier = suffixSupplier;
        return this;
    }

    @Override
    public String toString() {
        return logger.getName();
    }
}
